package com.atguigu.web;

import com.atguigu.dao.BookDao;
import com.atguigu.pojo.Book;
import com.atguigu.pojo.Page;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClientBookServlet extends BaseServlet{

    BookService bookService = new BookServiceImpl();
    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo ,pageSize;
        //1.获取请求的参数
        if(request.getParameter("pageNo") == null){
            pageNo = 1;
        }else{
            pageNo = Integer.valueOf(request.getParameter("pageNo"));
        }

        if(request.getParameter("pageSize") == null){
            pageSize = Page.PAGE_SIZE;
        }else{
            pageSize = Integer.valueOf(request.getParameter("pageSize"));
        }
        //2.调用BookService.page方法:Page对象
        Page<Book> page = bookService.page(pageNo,pageSize);

        page.setUrl("client/bookServlet?action=page");
        //3.保存page对象到request域中
        request.setAttribute("page",page);
        //4.请求转发到pages/manager/book_manager.jsp域中
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);
    }

    protected void pageByPrice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo ,pageSize;
        //1.获取请求的参数
        pageNo = WebUtils.parseInt(request.getParameter("pageNo"),1);
        pageSize = WebUtils.parseInt(request.getParameter("pageSize"),Page.PAGE_SIZE);

        int min = WebUtils.parseInt(request.getParameter("min"),0);
        int max = WebUtils.parseInt(request.getParameter("max"),Integer.MAX_VALUE);
        //2.调用BookService.page方法:Page对象
        Page<Book> page = bookService.pageByPrice(pageNo,pageSize,min,max);

        StringBuffer sb = new StringBuffer("client/bookServlet?action=pageByPrice");
        //如果有最小价格的参数,追加到分页条的地址参数中
        if(request.getParameter("min") !=null){
            sb.append("&min=").append(request.getParameter("min"));
        }

        //如果有最大价格的参数,追加到分页条的地址参数中
        if(request.getParameter("max") !=null){
            sb.append("&max=").append(request.getParameter("max"));
        }

        page.setUrl(sb.toString());
        //3.保存page对象到request域中
        request.setAttribute("page",page);
        //4.请求转发到pages/manager/book_manager.jsp域中
        request.getRequestDispatcher("/pages/client/index.jsp").forward(request,response);
    }

}
